#include "AudioSystem.h"

using namespace std;

AudioSystem::AudioSystem()
{
	format.wFormatTag = WAVE_FORMAT_PCM;
	format.nChannels  = 2;
	format.nSamplesPerSec  = 24000;
	format.wBitsPerSample = 8;
	format.nBlockAlign = (2*((format.wBitsPerSample)/8));
	format.nAvgBytesPerSec = format.nSamplesPerSec * format.nBlockAlign;
	format.cbSize = 0;

	currentBuffer = 0;
	waveOutOpen(&audioDevice, WAVE_MAPPER, &format, 0, 0, CALLBACK_NULL);
	waveInOpen(&inputDevice, WAVE_MAPPER,&format,0, 0, CALLBACK_NULL);
}

void AudioSystem::recorder(char * audioBuffer, int length)
{
	if (currentBuffer == NUM_OF_BUFFERS)
		currentBuffer = 0;
	bufferData[currentBuffer] = (char *)malloc(length);
	memcpy(bufferData[currentBuffer], audioBuffer, length);

	headers[currentBuffer].lpData = bufferData[currentBuffer];
	headers[currentBuffer].dwBufferLength = length;
	headers[currentBuffer].dwBytesRecorded =  0;
	headers[currentBuffer].dwUser = 0;
	headers[currentBuffer].dwFlags = 0;
	headers[currentBuffer].dwLoops = 0;

	if (waveInPrepareHeader(inputDevice,&headers[currentBuffer],sizeof(headers[currentBuffer])) != MMSYSERR_NOERROR)
	{
		cout << "ERROR";
	}
	if (waveInAddBuffer(inputDevice, &headers[currentBuffer], sizeof(headers[currentBuffer])) != MMSYSERR_NOERROR)
	{
		cout << "ERROR";
	}

	if(waveInStart(inputDevice) != MMSYSERR_NOERROR )
	{
		cout << "ERROR";
	}

	// Wait until finished recording
	 do 
	 {
		 Sleep(100);
	 } 
	 while (!(headers[currentBuffer].dwFlags& WHDR_DONE));

	if(waveInUnprepareHeader(inputDevice, &headers[currentBuffer], sizeof(headers[currentBuffer])) != MMSYSERR_NOERROR)
	{
		cout << "ERROR";
	}
	currentBuffer++;
}


void AudioSystem::playBuffer(char* audioBuffer, int length)
{
	
	if (currentBuffer == NUM_OF_BUFFERS)
		currentBuffer = 0;
	/*bufferData[currentBuffer] = (char *)malloc(length);
	memcpy(bufferData[currentBuffer], audioBuffer, length);

	headers[currentBuffer].lpData = bufferData[currentBuffer];
	headers[currentBuffer].dwBufferLength = length;
	headers[currentBuffer].dwBytesRecorded =  0;
	headers[currentBuffer].dwUser = 0;
	headers[currentBuffer].dwFlags = 0;
	headers[currentBuffer].dwLoops = 0;*/

	
	if (waveOutPrepareHeader(audioDevice,&headers[currentBuffer],sizeof(headers[currentBuffer])) != MMSYSERR_NOERROR)
	{
		cout << "ERROR";
	}
	if (waveOutWrite(audioDevice,&headers[currentBuffer],sizeof(headers[currentBuffer])) != MMSYSERR_NOERROR)
	{
		cout << "ERROR";
	}
	currentBuffer++;
}